import 'dart:async';
import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mfkb/config/Config.dart';
import 'package:mfkb/pages/home.dart';
import 'package:mfkb/pages/modules/login/InputField.dart';
import 'package:mfkb/pages/root.dart';
import 'package:mfkb/pages/userinfo.dart';
import 'package:mfkb/plugin/MyBehavior.dart';
import 'package:mfkb/service/SchoolService.dart';
import 'package:mfkb/service/UserService.dart';
import 'package:toast/toast.dart';

/**
 * 登录页面
 */
class LoginWidge extends StatefulWidget {
  @override
  _LoginWidgeState createState() => _LoginWidgeState();
}

class _LoginWidgeState extends State<LoginWidge> {

  bool show = false ;
  bool loading = false ;
  var username = null ;
  var password = null ;
  var school = null ;
  var school_name = null ;

  var _timer = null ;
  double _height = 179 ;

  var _current = 0 ;
  var _school_in = null ;

  var data = null ;

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark ,
      child: WillPopScope(
        child: Scaffold(
          resizeToAvoidBottomPadding: false ,
          body: Stack(
            children: <Widget>[
              Container(
                width:ScreenUtil().setWidth(375) ,
                color: Color.fromARGB(255 , 246, 245, 248)  ,
                child:Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    // 欢迎文字
                    Container(
                      //width:208 ,
                      height:ScreenUtil().setHeight(74) ,
                      margin: EdgeInsets.only(top:ScreenUtil().setHeight(108) , left:ScreenUtil().setWidth(31)),
                      child: Text(
                        "同学你好！\n欢迎来到觅风课表" ,
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(26) ,
                          color:Colors.black ,
                          fontWeight: FontWeight.w600 ,
                          height:ScreenUtil().setHeight(37) / ScreenUtil().setSp(26)
                        ),
                      ),
                    ) ,
                    // 学校选择器
                    Listener(
                      child: Container(
                        width: ScreenUtil().setWidth(320),
                        height: ScreenUtil().setHeight(50.0),
                        margin: EdgeInsets.only(top:ScreenUtil().setHeight(44) , left:ScreenUtil().setWidth(28)),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(8.0)) ,
                          color: Colors.white
                        ),
                        child: InputField(
                          txt:school_name ?? "请选择学校" , 
                          leftIcon:"assets/images/school.png" , 
                          rightIcon:"assets/images/more.png" , 
                          input:false ,
                        )
                      ),
                      onPointerDown: (event){
                        setState(() {
                          show = true ;
                        });
                      }
                    ) ,
                    Container(
                      width: ScreenUtil().setWidth(320),
                      height: ScreenUtil().setHeight(50.0),
                      margin: EdgeInsets.only(top:ScreenUtil().setHeight(14) , left:ScreenUtil().setWidth(28)),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(8.0)) ,
                        color: Colors.white
                      ),
                      child: InputField(
                        txt:"学生号" , 
                        leftIcon:"assets/images/xh.png" , 
                        input:true ,
                        onComplate: (value){
                          username = value ;
                        }
                      )
                    ),
                    Container(
                      width: ScreenUtil().setWidth(320),
                      height: ScreenUtil().setHeight(50.0),
                      margin: EdgeInsets.only(top:ScreenUtil().setHeight(14) , left:ScreenUtil().setWidth(28)),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(8.0)) ,
                        color: Colors.white
                      ),
                      child: InputField(
                        txt:"请输入教务管理密码" , 
                        leftIcon:"assets/images/pwd.png" , 
                        input:true , 
                        password:true ,
                        onComplate: (value){
                          password = value ;
                        }
                      )
                    ),
                    GestureDetector(
                      child: Container(
                        width: ScreenUtil().setWidth(326),
                        height: ScreenUtil().setHeight(48),
                        margin: EdgeInsets.only(top:ScreenUtil().setHeight(42) , left:ScreenUtil().setWidth(28)),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(8.0)) ,
                          color: Color.fromARGB(255, 0, 195, 206)
                        ),
                        child: Center(
                          child: Text("登录" , style: TextStyle(
                            fontSize: 18 ,
                            color:Colors.white ,
                            fontFamily: "Alibaba-PuHuiTi-M,Alibaba-PuHuiTi" ,
                            fontWeight: FontWeight.normal
                          ),),
                        )
                      ),
                      onTap: () async{
                        FocusScope.of(context).requestFocus(FocusNode());
                        if(username == null || username.trim() == ""){
                          Toast.show("请输入学号", context) ;
                          return ;
                        }else if(password == null || password.trim() == ""){
                          Toast.show("请输入密码", context) ;
                          return ;
                        }else if(school == null){
                          Toast.show("请选择学校", context) ;
                          return ;
                        }
                        setState(() {
                          loading = true ;
                        });
                        dynamic data = await UserService().login(username.toString().trim(), password.toString().trim(), school.toString()) ;
                        setState(() {
                          loading = false ;
                        });
                        if(data["code"] == 200){
                          await Config().getSpf().clear() ;
                          Config().setUserInfo(data["data"]) ;
                          if(data["data"]["nickname"] == null || data["data"]["nickname"] == ""
                           || data["data"]["icon"] == null || data["data"]["icon"] == "" 
                           || data["data"]["gender"] == null || data["data"]["gender"] == ""){
                            //Navigator.of(context).pop() ;
                            Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_){
                              return UserFullDataPage() ;
                            })) ;
                          }else{
                            Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_){
                              return NavitorBar() ;
                            })) ;
                          }
                        }else{
                          Toast.show(data["msg"], context) ;
                        }
                      },
                    )
                  ],
                )
              ) ,
              Visibility(
                visible: show,
                child: GestureDetector(
                  child: Container(
                    width:ScreenUtil().setWidth(375) ,
                    color: Color.fromARGB(150 , 0, 0, 0)  ,
                    child: GestureDetector(
                      child:Container(
                        width:ScreenUtil().setWidth(375) ,
                        margin: EdgeInsets.only(top:ScreenUtil().setHeight(_height)),
                        decoration: BoxDecoration(
                          color: Colors.white ,
                          borderRadius: BorderRadius.only(topLeft: Radius.circular(20.0) , topRight: Radius.circular(20.0))
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              height:26,
                              //color: Colors.red,
                              margin: EdgeInsets.only(top:ScreenUtil().setHeight(20) , left:ScreenUtil().setWidth(23)),
                              child: Text("选择你所在的学校" , style: TextStyle(
                                fontSize: 20 ,
                                height:1.34 ,
                                fontFamily: "PingFangSC-Semibold,PingFang SC" ,
                                fontWeight: FontWeight.w600
                              ),),
                            ) ,
                            Container(
                              height:ScreenUtil().setHeight(40),
                              width: ScreenUtil().setWidth(330),
                              //color: Colors.red,
                              margin: EdgeInsets.only(left:ScreenUtil().setHeight(23) , right:ScreenUtil().setWidth(22) , top:ScreenUtil().setHeight(22)),
                              decoration: BoxDecoration(
                                color: Color.fromARGB(255, 246, 246, 251) ,
                                borderRadius: BorderRadius.all(Radius.circular(8))
                              ),
                              child: Row(
                                children: <Widget>[
                                  Container(
                                    width: ScreenUtil().setWidth(18),
                                    height: ScreenUtil().setHeight(20),
                                    margin: EdgeInsets.only(left:ScreenUtil().setWidth(16)),
                                    child: Image.asset("assets/images/search.png" , fit: BoxFit.fill,),
                                  ) ,
                                  Expanded(
                                    child: Container(
                                      margin: EdgeInsets.only(left:ScreenUtil().setWidth(10)),
                                      height: ScreenUtil().setHeight(27),
                                      //color: Colors.red ,
                                      child: TextField(
                                        decoration: InputDecoration(
                                          border: InputBorder.none,
                                          hintText: _school_in ?? "请输入学校的名称" ,
                                          hintStyle: TextStyle(
                                            height: 0.2 ,
                                            fontSize: 14
                                          )
                                        ),
                                        onChanged:(value){
                                          _school_in = value ;
                                          // 进行搜搜操作
                                        },
                                      ),
                                    )
                                  )
                                ],
                              )
                            ) ,
                            Expanded(
                              child:handler()
                            )
                          ],
                        ),
                      ) ,
                      onTap: (){
                        
                      },
                      onVerticalDragUpdate: (DragUpdateDetails details) {
                        setState(() {
                          _height += details.delta.dy ; 
                          if(_height <= 179){
                            _height = 179 ;
                          }
                        });
                      } ,
                      onVerticalDragEnd: (details) {
                        setState(() {
                          if(new DateTime.now().millisecondsSinceEpoch - _current < 100){
                            show = false ;
                            _height = 179 ;
                            return ;
                          }
                          if(_height - 179 > 100){
                            show = false ;
                            _height = 179 ;
                          }else{
                            _height = 179 ;
                          }
                        });
                      } ,
                      onVerticalDragStart: (e){
                        _current = new DateTime.now().millisecondsSinceEpoch ;
                      },
                    )
                  ),
                  onTap: (){
                    setState(() {
                      show = false ;
                    });
                  },
                )
              ) ,
              Visibility(
                visible: loading ,
                child: GestureDetector(
                  child: Container(
                    width:ScreenUtil().setWidth(375) ,
                    color: Color.fromARGB(150 , 0, 0, 0)  ,
                    child: Center(
                      child: Container(
                        width: ScreenUtil().setWidth(200),
                        height: ScreenUtil().setHeight(200),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(20))
                        ),
                        child: Center(
                          child: Text("正在登陆..." , style: TextStyle(
                            fontSize: 16
                          ),),
                        ),
                      ),
                    )
                  ),
                )
              )
            ],
          ),
        ),
        onWillPop: (){
          if(show){
            setState(() {
              show = false ;
            });
            return Future.value(false) ;
          }
          return Future.value(true) ;
        },
      )
    ) ;
  }

  handler(){
    if(data == null){
      return FutureBuilder(
        future: SchoolService().getData(),
        builder: (BuildContext context, AsyncSnapshot<dynamic> snap){
          if(snap.hasData){
            data = snap.data ;
            return ScrollConfiguration(
              behavior: MyBehavior() ,
              child: list(snap.data)
            ) ;
          }else{
            return Center(child: Text("加载中..."),) ;
          }
        },
      ) ;
    }else{
      return ScrollConfiguration(
        behavior: MyBehavior() ,
        child: list(data)
      ) ;
    }
  }

  list(d){
    return ListView.builder(
      itemCount: d["data"].length ,
      itemBuilder: (context , index){
        return GestureDetector(
          child: Container(
            height: ScreenUtil().setHeight(50) + 1 ,
            margin: EdgeInsets.only(left:ScreenUtil().setWidth(31) , right:ScreenUtil().setWidth(15)),
            child: Column(
              children: <Widget>[
                Container(
                  height: ScreenUtil().setHeight(50) ,
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          height: 20 ,
                          child: Text(
                            d["data"][index]["name"] , style: TextStyle(
                              fontSize: 14 ,
                              height:1.3 ,
                              color: Color.fromARGB(255, 121, 132, 155) ,
                              fontFamily: "PingFang-SC-Bold,PingFang-SC" ,
                              fontWeight: FontWeight.bold
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        )
                      ) ,
                      Container(
                        width:ScreenUtil().setWidth(16) ,
                        height: ScreenUtil().setHeight(16) ,
                        child: Image.asset("assets/images/more_2x.png"),
                      )
                    ],
                  ),
                ) ,
                Container(
                //  margin: EdgeInsets.only(left:ScreenUtil().setWidth(31) , right:ScreenUtil().setWidth(15)),
                  height: 1 ,
                  color: Color.fromARGB(255, 236, 237, 241),
                )
              ],
            )
          ),
          onTap: (){
            school = d["data"][index]["id"] ;
            _school_in = d["data"][index]["name"] ;
            school_name = d["data"][index]["name"] ; 
            show = false ;
            setState(() {
              
            });
          },
        ) ;
      },
    ) ;
  }
}